package mspbots.autotask.data.core.servicecall;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

@Log4j2
@Component
@RequiredArgsConstructor
public class ServiceLevelAgreementResultsReceiver {

    private final ServiceLevelAgreementResultsRepository serviceLevelAgreementResultsRepository;

    @RabbitListener(queues = "auto-task.service-level-agreement-results.sync")
    public void syncTask(ResultMsg content) {

        ServiceLevelAgreementResults data = ServiceLevelAgreementResults.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .createdTime(content.getSyncDate())
                .updatedTime(LocalDateTime.now())
                .build();

        this.serviceLevelAgreementResultsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .switchIfEmpty(this.serviceLevelAgreementResultsRepository.save(data))
                .filter(old -> old.getUpdatedTime().isBefore(data.getUpdatedTime()))
                .map(old -> {
                    data.setId(old.getId());
                    return data;
                })
                .flatMap(this.serviceLevelAgreementResultsRepository::save)
                .block(Duration.ofSeconds(10));

    }
}
